package mbp.logger;

import jade.core.AID;
import jade.core.Agent;
import jade.lang.acl.ACLMessage;

import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import pl.edu.agh.logview.webservice.MessageBean;
import pl.edu.agh.logview.webservice.MessageBeanImpl;


public class LoggerProxy {

	private static final String RECEIVE = "ODEBRANIE";
	private static final String STATE = "STAN";
	private static final String SEND = "WYSLANIE";
	
	private static BlockingQueue<MessageBean> loggerQueue=new LinkedBlockingQueue<MessageBean>();	

	private static Date getTime (){
		Calendar cal = Calendar.getInstance();
		return cal.getTime();
	}
	
	public static MessageBean takeMessage() throws InterruptedException {
		return loggerQueue.take();
	}
	
	public static void logReceiving(ACLMessage message, Agent agent) {
		
		String sender = message.getSender().getName();
		String receiver = agent.getName();
		String content = message.getContent();

		//printToConsole(RECEIVE, sender, receiver, content);
		loggerQueue.add(new MessageBeanImpl(RECEIVE, content, getTime(), sender, receiver));
		

	}

	public static void logStateChange(String newState, Agent agent) {
		String agentName = agent.getName();
		//printToConsole(agentName, newState);
		loggerQueue.add(new MessageBeanImpl(STATE, newState, getTime(), agentName, null));

	}

	public static void logSending(ACLMessage message, Agent agent) {
		String sender = agent.getAID().getName();
		String receiver = ((AID) (message.getAllIntendedReceiver().next()))
				.getName();
		String content = message.getContent();

		//printToConsole(SEND, sender, receiver, content);
		loggerQueue.add(new MessageBeanImpl(SEND, content, getTime(), sender, receiver));
		
	}	

	
	private static void printToConsole(String logType, String sender,
			String receiver, String content) {
		System.out.println("****************\n" + logType + "\n"
				+ "FROM: " + sender + "\n" + "TO: " + receiver + "\n"
				+ "CONTENT: " + content + "\n" + "****************\n");
	}

	private static void printToConsole(String agentName, String newState) {
		System.out.println("****************\n" + "AGENT: " + agentName + "\n"
				+ "NEWSTATE: " + newState + "\n" + "****************\n");
	}
}
